var SEP = "\t";
var BASE = null;

function completeYourAlbum() {
  init();
  debug("Connecting...");
  setTimeout(completeYourAlbumRest,'1000');
}

function completeYourAlbumRest() {
  sendMsg('Echo',"completeYourAlbumRestRest", { msg:'dummy'});
}

function completeYourAlbumRestRest() {
  getArtists();
  debug("Connected");
}

function init() {
  BASE = (document.location+"").replace(/\/[^\/]+$/,'/');
}

function debug(msg) {
  $('debug').innerHTML = msg;
}

/** Makes an 'em' tag with innerHTML 'msg'. */
function em(msg) {
  return '<em>' + msg + '</em>';
}

/** Trims the whitespace of 's'. */
function trim(s) {
  s = s.replace(/^\s+/,"");
  s = s.replace(/\s+$/,"");
  return s;
}

/** Sets the style of 'el' to something signifying it was not fonud. */
function notFound(el) {
  el.style.fontStyle = "italic";
  el.style.color = "#770000";
  return el;
}

function newOption(sel,name) {
  var el = $n("option",sel);
  el.innerHTML = name;
  return el;
}

/** Returns 'true' if 'arr' contains 'v'. */
function arrayContains(arr,v) {
  for (var i=0; i<arr.length; i++) {
    if (arr[i] == v) return true;
  }
  return false;
}

/** Returns "s" if lst.length is not '1'. */
function pl(lst) {
  return lst.length == 1 ? "" : "s";
}

function getArtists() {
  sendMsg('GetArtists',"showArtists", {  });
}

function showArtists(msg) {
  var vs = msg.split(SEP);
  debug("Found " + vs.length + " artist" + pl(vs));
  var sel = $("artistList");
  removeAll(sel);
  for (var i=0; i<vs.length; i++) {
    var v = vs[i];
    var el = newOption(sel,v);
    el.onmousedown = newGetAlbumsFunction(v);
  }
}

function newGetAlbumsFunction(name) {
  var _name = name;
  return function() {
    getAlbums(_name);
  };
}

function getAlbums(name) {
  sendMsg('GetAlbums',"showAlbums", {  name:name });
}

function showAlbums(msg) {
  var vs = msg.split(SEP);
  debug("Found " + vs.length + " album" + pl(vs));
  var artist = vs[0];
  var sel = $("albumList");
  removeAll($("trackList"));
  removeAll(sel);
  var names = [];
  for (var i=1; i<vs.length; i++) {
    var v = vs[i];
    names.push(v);
    var el = newOption(sel,v);
    el.onmousedown = newGetTracksFunction(artist,v);
  }
  
  // Get the albums we don't have
  var url = BASE + 'getInfo.php';
  var params = 'artist=' + escape(artist);
  debug("Looking up artist " + em(artist));
  new Ajax.Request(url, { 
    method: 'get',
        parameters: params,
        onSuccess: newGetArtistsSuccess(names,artist)
    });
}

function newGetArtistsSuccess(vs,artist) {
  var _vs = vs;
  var _artist = artist;
  return function(res) {
    if (!res) return;
    var doc = res.responseXML.documentElement;
    var ns = doc.getElementsByTagName("album");
    var names = [];
    for (var i=0; i<ns.length; i++) {
      var n = ns[i];
      var name = trim(n.getAttribute("name"));
      var url = n.getAttribute("url");
      if (name && name != "" && !arrayContains(vs,name)) {
        names.push(name);
      }
    }
    debug("Found " + names.length + " album " + pl(names) + " for " + em(artist));
    var sel = $("albumList");
    for (var i=0; i<names.length; i++) {
      var name = names[i];
      var el = notFound(newOption(sel,name));
      el.onmousedown = newGetNewTracksFunction(artist,name);
    }
  }
}

function newGetNewTracksFunction(artist,album) {
  var _artist = artist;
  var _album = album;
  var url = BASE + 'getInfo.php';
  var params = 'artist=' + escape(artist) + "&album=" + escape(album);
  debug("Looking up " + em(album) + " by " + em(artist));
  return function(e) {
    new Ajax.Request(url, { 
      method: 'get',
          parameters: params,
          onSuccess: newGetNewTracksSuccess(_artist,_album)
          });
  };
}

function newGetNewTracksSuccess(artist,album) {
  var _artist = artist;
  var _album = album;
  return function(res) {
    if (!res) return;
    var doc = res.responseXML.documentElement;
    var sel = $("trackList");
    removeAll(sel);
    var ns = doc.getElementsByTagName("track");
    debug("Found " + ns.length + " track" + pl(ns) + " for " + em(_album));
    for (var i=0; i<ns.length; i++) {
      var n = ns[i];
      var name = trim(n.getAttribute("name"));
      var el = notFound(newOption(sel,name));
    }
  }
}


function newGetTracksFunction(artist,name) {
  var _artist = artist;
  var _name = name;
  return function() {
    getTracks(_artist,_name);
  };
}

function getTracks(artist,name) {
  sendMsg('GetTracks',"showTracks", {  artist:artist, name:name });
}

function showTracks(msg) {
  var vs = msg.split(SEP);
  var artist = vs[0];
  var album = vs[1];
  debug("Found " + vs.length + " track" + pl(vs) + " for " + em(artist));
  var sel = $("trackList");
  removeAll(sel);
  var names = [];
  for (var i=2; i<vs.length; i++) {
    var v = vs[i];
    names.push(v);
    var el = newOption(sel,v);
  }

  // Get the tracks we don't have
  var url = BASE + 'getInfo.php';
  var params = 'artist=' + escape(artist) + "&album=" + escape(album);
  debug("Looking up " + em(album) + " by  " + em(artist));
  new Ajax.Request(url, { 
    method: 'get',
        parameters: params,
        onSuccess: newGetTracksSuccess(names,artist,album)
    });
}

function newGetTracksSuccess(vs,artist,album) {
  var _vs = vs;
  var _artist = artist;
  var _album = album;
  return function(res) {
    if (!res) return;
    var doc = res.responseXML.documentElement;
    var ns = doc.getElementsByTagName("track");
    var names = [];
    for (var i=0; i<ns.length; i++) {
      var n = ns[i];
      var name = trim(n.getAttribute("name"));
      if (name && name != "" && !arrayContains(vs,name)) {
        names.push(name);
      }
    }
    debug("Found " + names.length + " track " + pl(names) + " for " + em(album));
    var sel = $("trackList");
    for (var i=0; i<names.length; i++) {
      var name = names[i];
      var el = notFound(newOption(sel,name));
    }
  }
}

function removeAll(el) {
  while (el.childNodes.length > 0) {
    el.removeChild(el.firstChild);
  }
}

function $n(id,on) {
  var el = document.createElement(id);
  if (on) on.appendChild(el);
  return el;
}
